# Copyright (c) 2024 Alibaba Inc (authors: Xiang Lyu)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from functools import partial
from typing import Generator
import json
import onnxruntime
import torch
import numpy as np
import whisper
from typing import Callable
import torchaudio.compliance.kaldi as kaldi
import torchaudio
import os
import re
import inflect
from loguru import logger
import pickle
try:
    import ttsfrd
    use_ttsfrd = True
except ImportError:
    print("failed to import ttsfrd, use WeTextProcessing instead")
    from tn.chinese.normalizer import Normalizer as ZhNormalizer
    from tn.english.normalizer import Normalizer as EnNormalizer
    use_ttsfrd = False
from cosyvoice.utils.file_utils import logging
from cosyvoice.utils.frontend_utils import contains_chinese, replace_blank, replace_corner_mark, remove_bracket, spell_out_number, split_paragraph, is_only_punctuation


class CosyVoiceFrontEnd:

    def __init__(self,
                 get_tokenizer: Callable,
                 feat_extractor: Callable,
                 campplus_model: str,
                 speech_tokenizer_model: str,
                 spk2info: str = '',
                 allowed_special: str = 'all',
                 model_version: str = 'CosyVoice1'):
        self.model_version = model_version
        self.tokenizer = get_tokenizer()
        self.feat_extractor = feat_extractor
        self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
        option = onnxruntime.SessionOptions()
        option.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_ENABLE_ALL
        option.intra_op_num_threads = 1
        self.campplus_session = onnxruntime.InferenceSession(campplus_model, sess_options=option, providers=["CPUExecutionProvider"])
        self.speech_tokenizer_session = onnxruntime.InferenceSession(speech_tokenizer_model, sess_options=option,
                                                                     providers=["CUDAExecutionProvider" if torch.cuda.is_available() else
                                                                                "CPUExecutionProvider"])
        if os.path.exists(spk2info):
            self.spk2info = torch.load(spk2info, map_location=self.device)
        else:
            self.spk2info = {}
        self.allowed_special = allowed_special
        self.use_ttsfrd = use_ttsfrd
        if self.use_ttsfrd:
            self.frd = ttsfrd.TtsFrontendEngine()
            ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
            assert self.frd.initialize('{}/../../pretrained_models/CosyVoice-ttsfrd/resource'.format(ROOT_DIR)) is True, \
                'failed to initialize ttsfrd resource'
            self.frd.set_lang_type('pinyinvg')
        else:
            self.zh_tn_model = ZhNormalizer(remove_erhua=False, full_to_half=False)
            self.en_tn_model = EnNormalizer()
            self.inflect_parser = inflect.engine()

    def _extract_text_token(self, text):
        if isinstance(text, Generator):
            logging.info('get tts_text generator, will return _extract_text_token_generator!')
            # NOTE add a dummy text_token_len for compatibility
            return self._extract_text_token_generator(text), torch.tensor([0], dtype=torch.int32).to(self.device)
        else:
            text_token = self.tokenizer.encode(text, allowed_special=self.allowed_special)
            text_token = torch.tensor([text_token], dtype=torch.int32).to(self.device)
            text_token_len = torch.tensor([text_token.shape[1]], dtype=torch.int32).to(self.device)
            return text_token, text_token_len
    
    def _extract_text_token_generator(self, text_generator):
        for text in text_generator:
            text_token, _ = self._extract_text_token(text)
            for i in range(text_token.shape[1]):
                yield text_token[:, i: i + 1]

    def _get_token_cache_path(self, uid, timbre_id):
        # 通过{uid}_{timbre_id} 生成缓存文件名
        cache_dir = './speech_token_cache'
        os.makedirs(cache_dir, exist_ok=True)
        return f'{cache_dir}/{uid}_{timbre_id}.pkl'

    def _extract_speech_token(self, uid, timbre_id, speech):
        assert speech.shape[1] / 16000 <= 30, 'do not support extract speech token for audio longer than 30s'
        if self.model_version == 'CosyVoice1':
            # 检查缓存文件是否存在
            cache_path = self._get_token_cache_path(uid, timbre_id)
            if os.path.exists(cache_path):
                logger.debug(f"从缓存中加载语音token: {cache_path}")
                with open(cache_path, 'rb') as f:
                    speech_token, speech_token_len = pickle.load(f)
                return speech_token, speech_token_len
        feat = whisper.log_mel_spectrogram(speech, n_mels=128)
        speech_token = self.speech_tokenizer_session.run(None,
                                                         {self.speech_tokenizer_session.get_inputs()[0].name:
                                                          feat.detach().cpu().numpy(),
                                                          self.speech_tokenizer_session.get_inputs()[1].name:
                                                          np.array([feat.shape[2]], dtype=np.int32)})[0].flatten().tolist()
        speech_token = torch.tensor([speech_token], dtype=torch.int32).to(self.device)
        speech_token_len = torch.tensor([speech_token.shape[1]], dtype=torch.int32).to(self.device)
        if self.model_version == 'CosyVoice1':
            # 保存结果到缓存文件
            with open(cache_path, 'wb') as f:
                pickle.dump((speech_token, speech_token_len), f)
            logger.debug(f"保存语音token到缓存: {cache_path}")
        return speech_token, speech_token_len

    def _extract_spk_embedding(self, speech):
        feat = kaldi.fbank(speech,
                           num_mel_bins=80,
                           dither=0,
                           sample_frequency=16000)
        feat = feat - feat.mean(dim=0, keepdim=True)
        embedding = self.campplus_session.run(None,
                                              {self.campplus_session.get_inputs()[0].name: feat.unsqueeze(dim=0).cpu().numpy()})[0].flatten().tolist()
        embedding = torch.tensor([embedding]).to(self.device)
        return embedding

    def _extract_speech_feat(self, speech):
        speech_feat = self.feat_extractor(speech).squeeze(dim=0).transpose(0, 1).to(self.device)
        speech_feat = speech_feat.unsqueeze(dim=0)
        speech_feat_len = torch.tensor([speech_feat.shape[1]], dtype=torch.int32).to(self.device)
        return speech_feat, speech_feat_len

    def add_language_prefix(self, text):
        lang_char_sets = {
            '<|zh|>': '[\u4e00-\u9fff]',
            '<|en|>': '[a-zA-Z]',
            '<|jp|>': '[\u3040-\u30ff\u31f0-\u31ff]',
            '<|ko|>': '[\uac00-\ud7af\u1100-\u11ff]'
        }

        def determine_language(segment):
            lang_counts = {lang: len(re.findall(char_set, segment)) for lang, char_set in lang_char_sets.items()}
            return max(lang_counts, key=lang_counts.get)

        total_counts = {lang: 0 for lang in lang_char_sets.keys()}
        for char in text:
            for lang, char_set in lang_char_sets.items():
                if re.match(char_set, char):
                    total_counts[lang] += 1
                    break
        predominant_language = max(total_counts, key=total_counts.get)
        predominant_count = total_counts[predominant_language]
        total_count = sum(total_counts.values())
        if predominant_count == total_count:
            return f"{predominant_language}{text}"

        def add_prefix(match):
            segment = match.group(0)
            lang = determine_language(segment)
            return f"{lang}{segment}" if lang else segment

        combined_pattern = re.compile(
            f"({'|'.join([f'({char_set})+' for char_set in lang_char_sets.values()])})"
        )
        result = re.sub(combined_pattern, add_prefix, text)

        delimiters = lang_char_sets.keys()
        parts = re.split('(?={})'.format('|'.join(re.escape(d) for d in delimiters)), result)
        parts = [p for p in parts if p]
        merged_parts = []
        last_l = ""
        for i in range(len(parts)):
            this_l = parts[i][0:6]
            if last_l == this_l:
                merged_parts.append(parts[i][6:])
            else:
                merged_parts.append(parts[i])
            last_l = this_l
        return ''.join(merged_parts)

    def text_normalize(self, text, split=True, text_frontend=True):
        if isinstance(text, Generator):
            logging.info('get tts_text generator, will skip text_normalize!')
            return [text]
        if text_frontend is False or text == '':
            return [text] if split is True else text
        text = text.strip()
        if self.use_ttsfrd:
            texts = [i["text"] for i in json.loads(self.frd.do_voicegen_frd(text))["sentences"]]
            text = ''.join(texts)
        else:
            if contains_chinese(text):
                text = self.zh_tn_model.normalize(text)
                text = text.replace("\n", "")
                text = replace_blank(text)
                text = replace_corner_mark(text)
                text = text.replace(".", "。")
                text = text.replace(" - ", "，")
                text = remove_bracket(text)
                text = re.sub(r'[，,、]+$', '。', text)
                texts = list(split_paragraph(text, partial(self.tokenizer.encode, allowed_special=self.allowed_special), "zh", token_max_n=80,
                                             token_min_n=60, merge_len=20, comma_split=False))
            else:
                text = self.en_tn_model.normalize(text)
                text = spell_out_number(text, self.inflect_parser)
                texts = list(split_paragraph(text, partial(self.tokenizer.encode, allowed_special=self.allowed_special), "en", token_max_n=50,
                                             token_min_n=30, merge_len=20, comma_split=False))
        if split is False:
            return text
        texts = [i for i in texts if not is_only_punctuation(i)]
        # TODO 需要测试cosyvoice1.0模型对于文本加语种前缀的推理效果（下面被注释的部分）
        # 如果用的是cosyvoice1.0的模型，需要加上语言标签
        if self.model_version == 'CosyVoice1':
            return [self.add_language_prefix(t) for t in texts]
        else:
            return texts
        # return texts

    def frontend_sft(self, tts_text, spk_id):
        tts_text_token, tts_text_token_len = self._extract_text_token(tts_text)
        embedding = self.spk2info[spk_id]['embedding']
        model_input = {'text': tts_text_token, 'text_len': tts_text_token_len, 'llm_embedding': embedding, 'flow_embedding': embedding}
        return model_input

    # def frontend_zero_shot(self, tts_text, prompt_text, prompt_speech_16k, speech_token, speech_token_len, resample_rate):
    #     tts_text_token, tts_text_token_len = self._extract_text_token(tts_text)
    #     prompt_text_token, prompt_text_token_len = self._extract_text_token(prompt_text)
    #     prompt_speech_resample = torchaudio.transforms.Resample(orig_freq=16000, new_freq=resample_rate)(prompt_speech_16k)
    #     speech_feat, speech_feat_len = self._extract_speech_feat(prompt_speech_resample)
    #     if resample_rate == 24000:
    #         # cosyvoice2, force speech_feat % speech_token = 2
    #         token_len = min(int(speech_feat.shape[1] / 2), speech_token.shape[1])
    #         speech_feat, speech_feat_len[:] = speech_feat[:, :2 * token_len], 2 * token_len
    #         speech_token, speech_token_len[:] = speech_token[:, :token_len], token_len
    #     embedding = self._extract_spk_embedding(prompt_speech_16k)
    #     model_input = {'text': tts_text_token, 'text_len': tts_text_token_len,
    #                    'prompt_text': prompt_text_token, 'prompt_text_len': prompt_text_token_len,
    #                    'llm_prompt_speech_token': speech_token, 'llm_prompt_speech_token_len': speech_token_len,
    #                    'flow_prompt_speech_token': speech_token, 'flow_prompt_speech_token_len': speech_token_len,
    #                    'prompt_speech_feat': speech_feat, 'prompt_speech_feat_len': speech_feat_len,
    #                    'llm_embedding': embedding, 'flow_embedding': embedding}
    #     return model_input

    def frontend_zero_shot(self, tts_text, prompt_text, prompt_speech_16k, speech_token, speech_token_len, resample_rate, zero_shot_spk_id):
        tts_text_token, tts_text_token_len = self._extract_text_token(tts_text)
        if zero_shot_spk_id == '':
            prompt_text_token, prompt_text_token_len = self._extract_text_token(prompt_text)
            prompt_speech_resample = torchaudio.transforms.Resample(orig_freq=16000, new_freq=resample_rate)(prompt_speech_16k)
            speech_feat, speech_feat_len = self._extract_speech_feat(prompt_speech_resample)
            if resample_rate == 24000:
                # cosyvoice2, force speech_feat % speech_token = 2
                token_len = min(int(speech_feat.shape[1] / 2), speech_token.shape[1])
                speech_feat, speech_feat_len[:] = speech_feat[:, :2 * token_len], 2 * token_len
                speech_token, speech_token_len[:] = speech_token[:, :token_len], token_len
            embedding = self._extract_spk_embedding(prompt_speech_16k)
            model_input = {'prompt_text': prompt_text_token, 'prompt_text_len': prompt_text_token_len,
                           'llm_prompt_speech_token': speech_token, 'llm_prompt_speech_token_len': speech_token_len,
                           'flow_prompt_speech_token': speech_token, 'flow_prompt_speech_token_len': speech_token_len,
                           'prompt_speech_feat': speech_feat, 'prompt_speech_feat_len': speech_feat_len,
                           'llm_embedding': embedding, 'flow_embedding': embedding}
        else:
            model_input = self.spk2info[zero_shot_spk_id]
        model_input['text'] = tts_text_token
        model_input['text_len'] = tts_text_token_len
        return model_input

    # def frontend_cross_lingual(self, tts_text, prompt_speech_16k, speech_token, speech_token_len, resample_rate):
    #     model_input = self.frontend_zero_shot(tts_text, '', prompt_speech_16k, speech_token, speech_token_len, resample_rate)
    #     # in cross lingual mode, we remove prompt in llm
    #     del model_input['prompt_text']
    #     del model_input['prompt_text_len']
    #     del model_input['llm_prompt_speech_token']
    #     del model_input['llm_prompt_speech_token_len']
    #     return model_input
    
    def frontend_cross_lingual(self, tts_text, prompt_speech_16k, speech_token, speech_token_len, resample_rate, zero_shot_spk_id):
        model_input = self.frontend_zero_shot(tts_text, '', prompt_speech_16k, speech_token, speech_token_len, resample_rate, zero_shot_spk_id)
        # in cross lingual mode, we remove prompt in llm
        del model_input['prompt_text']
        del model_input['prompt_text_len']
        del model_input['llm_prompt_speech_token']
        del model_input['llm_prompt_speech_token_len']
        return model_input

    def frontend_instruct(self, tts_text, spk_id, instruct_text):
        model_input = self.frontend_sft(tts_text, spk_id)
        # in instruct mode, we remove spk_embedding in llm due to information leakage
        del model_input['llm_embedding']
        instruct_text_token, instruct_text_token_len = self._extract_text_token(instruct_text + '<endofprompt>')
        model_input['prompt_text'] = instruct_text_token
        model_input['prompt_text_len'] = instruct_text_token_len
        return model_input

    def frontend_instruct2(self, tts_text, instruct_text, prompt_speech_16k, resample_rate, zero_shot_spk_id):
        model_input = self.frontend_zero_shot(tts_text, instruct_text + '<|endofprompt|>', prompt_speech_16k, resample_rate, zero_shot_spk_id)
        del model_input['llm_prompt_speech_token']
        del model_input['llm_prompt_speech_token_len']
        return model_input

    def frontend_vc(self, source_speech_16k, prompt_speech_16k, resample_rate):
        prompt_speech_token, prompt_speech_token_len = self._extract_speech_token(prompt_speech_16k)
        prompt_speech_resample = torchaudio.transforms.Resample(orig_freq=16000, new_freq=resample_rate)(prompt_speech_16k)
        prompt_speech_feat, prompt_speech_feat_len = self._extract_speech_feat(prompt_speech_resample)
        embedding = self._extract_spk_embedding(prompt_speech_16k)
        source_speech_token, source_speech_token_len = self._extract_speech_token(source_speech_16k)
        model_input = {'source_speech_token': source_speech_token, 'source_speech_token_len': source_speech_token_len,
                       'flow_prompt_speech_token': prompt_speech_token, 'flow_prompt_speech_token_len': prompt_speech_token_len,
                       'prompt_speech_feat': prompt_speech_feat, 'prompt_speech_feat_len': prompt_speech_feat_len,
                       'flow_embedding': embedding}
        return model_input